<?php
namespace Admin\Controller;
use Think\Controller;
class HospitalController extends IndexController{

    public function lists(){
       
        $type = I("request.type");
        if ($type == 1) {
            $data['name']=I("post.name");
            //===-=-=-=-=-=-=-=-=-=-=-=-=-=
            $cid=I("post.cid");
            $country=D("Country");
            $getCountry=$country->where('countryid='.$cid)->field("countryname_cn")->find();
            $data['country']=$getCountry['countryname_cn'];
            //=--=-=-=--=-=--==-=-=-=--=-=--=-=-=-
            $data['zid']=I("post.zid");
            $data['abstract']=I("post.abstract");
            $data['descrip']=I("post.descrip");
            $data['address']=I("post.address");
            $data['telephone']=I("post.telephone");
            $data['lat']=I("post.lat");
            $data['lng']=I("post.lng");
            $data['create_time']=time();
            $hospital = D("Hospital");
            if (is_array($_FILES['imgs'][0])||$_FILES['imgs']!=null) {
                //=================处理多图片上传==================
                header("content-type:text/html;charset=utf-8");
                $file = $_FILES;
                $newFile = array();
                foreach ($file as $key => $value) {
                    $num = count($value['name']);
                    for ($i = 0; $i < $num; $i++) {
                        $newFile[$i]['name'] = $value['name'][$i];
                        $newFile[$i]['type'] = $value['type'][$i];
                        $newFile[$i]['tmp_name'] = $value['tmp_name'][$i];
                        $newFile[$i]['error'] = $value['error'][$i];
                        $newFile[$i]['size'] = $value['size'][$i];
                    }
                }
                header("content-type:text/html;charset=utf-8");
                $upload = new \Think\Upload(); // 实例化上传类
                $upload->maxSize = 1024 * 1024 * 10;// 设置附件上传大小 (-1) 是不限值大小
                $upload->exts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
                $upload->rootPath = "./imagecn_xxHos/";
                //$upload->savePath = "./Hotel";// 设置附件上传目录
                $upload->replace = true; //存在同名文件是否是覆盖
                // 是否使用子目录保存上传文件
                $upload->autoSub = true;
                $info = $upload->upload($newFile);
                if (!$info) {
                    $data['imgs'] = "";
                } else {
                 //==============================
                    $path = '';
                    for ($i = 0; $i <= count($info) - 1; $i++) {
                        $path .= ltrim($info[$i]['savepath'], './') . $info[$i]['savename'] . ',';
                        $data['imgs'] = $path;
                    }
                }
            }


            if ($_FILES['logo_img'] !== null) {
                header("content-type:text/html;charset=utf-8");
                $upload = new \Think\Upload(); // 实例化上传类
                $upload->maxSize = 1024 * 1024 * 10;// 设置附件上传大小 (-1) 是不限值大小
                $upload->exts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
                $upload->rootPath = "./imagecn_Hos/";
                //$upload->savePath = "./Hotel";// 设置附件上传目录
                $upload->replace = true; //存在同名文件是否是覆盖
                // 是否使用子目录保存上传文件
                $upload->autoSub = true;
                $logoInfo = $upload->uploadOne($_FILES['logo_img']);
                if (!$logoInfo) {
                    $data['logo_img'] = "";
                } else {
                    //拼接上传的图片路径用于上传到服务器
                    $logoPath = '';
                    $logoPath .= ltrim($logoInfo['savepath'], './') . $logoInfo['savename'];
                    $data['logo_img'] = $logoPath;
                }
            }
            $res=$hospital->add($data);
            //记录兼职增加
             $log=D("Log");
             $opt['name']=$_SESSION['name'];
             $opt['action']='add';
             $opt['model']='Hospital';
             $opt['create_time']=time();
             $opt['log']='员工号为'.$_SESSION['name'].'对医院模块执行了增加操作,增加了id为'.$res;
             $log->add($opt);
            $this->redirect('Hospital/lists');
        } elseif ($type == 2) {
            $this->doupdate();
        }
        
        $this->display();
        

//       $xhprof_data = xhprof_disable();
//
//
//        $xhprof_runs = new \XHProfRuns_Default();
//
//        $run_id = $xhprof_runs->save_run($xhprof_data, "xhprof_foo");
//
//        $url = "./xhprof_html/index.php?run=$run_id&source=xhprof_foo";
//
//        echo '<a href="'.$url.'">'.$url.'</a>';
    }

    public function hos_list()
    {
        $hos = D("Hospital");
        $State = D("State");
        if(I("request.iDisplayStart")==''){

            $start=0;
        }else{
            $start=I("request.iDisplayStart");
        }
        if(I("request.sSearch")!=''){
            $map['name'] =  array('like','%'.I("request.sSearch").'%');

        }else{
            $map='';
        }
        $res = $hos->field("id,zid,country,name,logo_img,abstract,descrip,address,telephone,imgs,lat,lng")
            ->where($map)
            ->limit($start,I("request.iDisplayLength"))
            ->select();
        if (!$res) {
            echo json_encode(0);
            exit;
        }
        foreach ($res as &$v) {
            if ($v['zid'] != null) {
                $r = $State->where('id=' . $v['zid'])->find();
                $v['zid'] = $r['name'];
            }
        }
        $ret = array(
            "sEcho" => intval($_GET['sEcho']),
            "iTotalRecords" => $start,
            "iTotalDisplayRecords" => $hos->where($map)->count(),
            "aaData" => $res
        );

        echo json_encode($ret);exit;
    }

    public function add()   {
        $this->display();
    }

    //国家列表
    public function country_list()
    {
        $Country = D("Country");
        $r = $Country->select();
        if (!$r) {
            echo json_encode(0);
            exit;
        }
        echo json_encode($r);
        exit;
    }

    //城市列表
    public function city_list()
    {
        $cid = I("request.cid");
        $State = D("State");
        $r = $State->where('cid=' . $cid)->select();
        if (!$r) {
            echo json_encode(0);
            exit;
        }
        echo json_encode($r);
        exit;
    }

    public function del()
    {
        $id = I("request.id");
        $hos = D("Hospital");
        $r = $hos->where('id=' . $id)->find();
        if ($r['logo_img'] != null) {
            unlink("./imagecn_Hos/" . $r['logo_img']);
        }
        $res = $hos->where('id=' . $id)->delete();
        if (!$res) {
            echo json_encode(0);
            exit;
        }
        $log=D("Log");
             $opt['name']=$_SESSION['name'];
             $opt['action']='del';
             $opt['model']='Hospital';
             $opt['create_time']=time();
             $opt['log']='员工号为'.$_SESSION['name'].'对医院模块执行了删除操作,删除了id为'.$id;
             $log->add($opt);
        echo json_encode(1);
        exit;
    }

    public function update()
    {
        $id = I("request.id");
        setcookie("uid", $id, time() + 3600);
        $this->display();
    }

    public function update_list(){
        $id = $_COOKIE["uid"];
        $hos = D("Hospital");
        $r = $hos->where('id='.$id)->field('zid,name,country,logo_img,abstract,descrip,address,telephone,lat,lng')->find();
        if (!$r) {
            echo json_encode(0);
            exit;
        }
        
        echo json_encode($r);
        exit;
    }

    public function doupdate(){
        $country = D("Country");
        $data['name'] = I("post.name");
        $data['zid'] = I("post.zid");
        $data['abstract'] = I("post.abstract");
        $data['descrip'] = I("post.descrip");
        $data['address'] = I("post.address");
        $data['telephone'] = I("post.telephone");
        $data['lat'] = I("post.lat");
        $data['lng'] = I("post.lng");
        $cid = I("post.cid");
        $re = $country->where("countryid=" . $cid)->find();
        $data['country'] = $re['countryname_cn'];
        $hospital = D("Hospital");
        if ($_FILES['logo_img']['name'] != null) {
            if (isset($_COOKIE["uid"])) {
                $r = $hospital->where('id=' . $_COOKIE["uid"])->find();
                if ($r['logo_img'] != null) {
                    unlink("./imagecn_Hos/" . $r['logo_img']);
                }
            }
            header("content-type:text/html;charset=utf-8");

            $upload = new \Think\Upload(); // 实例化上传类

            $upload->maxSize = 1024 * 1024;// 设置附件上传大小 (-1) 是不限值大小
            $upload->exts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->rootPath ="./imagecn_Hos/";
           // $upload->savePath = "/Hos";// 设置附件上传目录
            $upload->replace = true; //存在同名文件是否是覆盖

            // 是否使用子目录保存上传文件
            $upload->autoSub = true;
            // 采用date函数生成命名规则 传入Y-m-d参数
            $upload->saveName = time() . '_' . mt_rand();
            $info = $upload->uploadOne($_FILES['logo_img']);
            if (!$info) {
                $data['logo_img'] = '';
            } else {
                $data['logo_img'] = ltrim($info['savepath'] . $info['savename'], '/');
            }
        }elseif (is_array($_FILES['imgs'][0])||$_FILES['imgs']!=null) {
                $file = $_FILES;
                $newFile = array();
                foreach ($file as $key => $value) {
                    $num = count($value['name']);
                    for ($i = 0; $i < $num; $i++) {
                        $newFile[$i]['name'] = $value['name'][$i];
                        $newFile[$i]['type'] = $value['type'][$i];
                        $newFile[$i]['tmp_name'] = $value['tmp_name'][$i];
                        $newFile[$i]['error'] = $value['error'][$i];
                        $newFile[$i]['size'] = $value['size'][$i];
                    }
                }
                header("content-type:text/html;charset=utf-8");

                $upload = new \Think\Upload(); // 实例化上传类
                $upload->maxSize = 1024 * 1024 * 10;// 设置附件上传大小 (-1) 是不限值大小
                $upload->exts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
                $upload->rootPath = "./imagecn_xxHos/";
                //$upload->savePath = "./Hotel";// 设置附件上传目录
                $upload->replace = true; //存在同名文件是否是覆盖
                // 是否使用子目录保存上传文件
                $upload->autoSub = true;
                $info = $upload->upload($newFile);
                if (!$info) {
                    $data['imgs'] = "";
                } else {
                    //拼接上传的图片路径用于上传到服务器
                    $path = '';
                    for ($i = 0; $i <= count($info) - 1; $i++) {
                        $path .= ltrim($info[$i]['savepath'], './') . $info[$i]['savename'] . ',';
                    }
                    if (isset($_COOKIE["uid"])) {
                        $getData = $hospital->where("id=" . $_COOKIE["uid"])->getField('imgs');
                    }

                    if ($path != null) {
                        $data['imgs'] = $path . $getData;
                    } else {
                        $data['imgs'] = $getData;
                    }
                }
            }

        if (isset($_COOKIE["uid"])) {
            $hospital->where("id=" . $_COOKIE["uid"])->save($data);
             $log=D("Log");
             $opt['name']=$_SESSION['name'];
             $opt['action']='update';
             $opt['model']='Hospital';
             $opt['create_time']=time();
             $opt['log']='员工号为'.$_SESSION['name'].'对医院模块执行了修改操作,修改了id为'.$_COOKIE["uid"];
             $log->add($opt);
            $this->redirect('Hospital/lists');
           
        }

    }

    public function update_imgs(){
        $id = $_COOKIE['uid'];
        $Hospital = D('Hospital');
        $type = I("request.type");
        if ($type == 1) {
            $re = $Hospital->where('id='.$id)->field('id,imgs')->find();
            //===================分隔图片地址&获取图片的拼接的总数量，==============================
            //==============================加上一个$tpye做判断===================================
           if(!empty($re['imgs'])) {//修改显示图片时加上判断，如果不判断，会在页面显示一个无法显示图片和删除按钮
                $arr = explode(',', rtrim($re['imgs'], ","));
                $num = count($arr);
                $result['id'] = $re['id'];
                $result['num'] = $num;

                //========================根据分割图片地址的获取的图片总数&把图片分配到图片数组=====================
                for ($i = 0; $i <= $num - 1; $i++) {
                    $result[$i]['imgs'] = $arr[$i];
                }

                if (!$result) {
                    echo json_encode(0);
                    exit;
                }
                echo json_encode($result);
                exit;
           }
        } elseif ($type == 2) {
            $imgNum = I("request.imgNum");
            $delNum = $imgNum;
            $id = $_COOKIE["uid"];
            $hospital = D("Hospital");
            $getImage = $hospital->where('id=' . $id)->field('imgs')->find();
            $arr = $getImage['imgs'];
            $str = str_replace($delNum . ',', "", $arr);
            $data['imgs'] = $str;
            unlink("./imagecn_xxHos/" . $delNum);

            if (isset($_COOKIE["uid"])) {
                $HospitalResult = $hospital->where("id=" . $_COOKIE["uid"])->save($data);
                if (!$HospitalResult) {
                    echo json_encode(0);
                    exit;
                } else {
                    $log=D("Log");
                    $opt['name']=$_SESSION['name'];
                    $opt['action']='del';
                    $opt['model']='Hospitalimg';
                    $opt['create_time']=time();
                    $opt['log']='员工号为'.$_SESSION['name'].'对医院图片模块执行了删除操作,删除了id为'.$_COOKIE["uid"];
                    $log->add($opt);
                    echo json_encode($HospitalResult);
                    exit;
                }
            }

        }
    }


//    public function strip(){
//        $Hospital=D('Hospital');
//        $abstract=$Hospital->field('abstract,id')->select();
//
//        if($abstract){
//
//            foreach($abstract as $key=>$value ){
//                //'&quot;
//                $replace=array(';;',';');
//                $value['abstract']=str_replace($replace,'',$value['abstract']);
//                $data['abstract']=$value['abstract'];
//
//
//               $Hospital->where("id=".$value['id'])->save($data);
//            }
//
//        }
//    }


//    public function delNull(){
//        $Hospital=D("Hospital");
//        $data['descrip']='';
//       $res= $Hospital->where("id=135")->save($data);
//        if($res){
//            echo "ok";
//        }
//    }
}